package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.server.mapper.SoundMapper;
import com.tanhua.server.mapper.UserRecordMapper;
import com.tanhua.server.pojo.Sound;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.pojo.UserRecord;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.SoundVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.Duration;
import java.util.List;
import java.util.Random;

@Service
public class SoundService {
    @Autowired
    private SoundMapper soundMapper;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserRecordMapper userRecordMapper;

    public void saveSound(MultipartFile soundFile) {
        User user = UserThreadLocal.get();
        Sound sound = new Sound();
        sound.setUserId(user.getId());

        try {
            //上传音频
            StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(),
                    StringUtils.substringAfter(soundFile.getOriginalFilename(), "."),
                    null);
            sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());

        } catch (Exception e) {
            e.printStackTrace();
        }
        this.soundMapper.insert(sound);
    }
    /**
     * 收到音频
     * @return
     */

    public SoundVo getSound() {

        User user = UserThreadLocal.get();

        QueryWrapper<Sound> wrapper = new QueryWrapper<>();
        //随机一位用户
       /* Long soundId = RandomUtil.randomEle(soundIds);*/
        int index;
        Random random = new Random();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",user.getId().intValue());
        while (true){
            index = random.nextInt(10)+1;
            List<UserRecord> list = this.userRecordMapper.selectList(queryWrapper);
            int flag=0; //没有重复
            for (int i = 0; i < list.size(); i++) {
                int now = list.get(i).getVoiceId();
                if(index==now){
                    flag=1; //已经推荐过了
                    break;
                }
            }
            if(flag==1) continue;
            else break;
        }
        wrapper.eq("id", index);
        Sound sound = this.soundMapper.selectOne(wrapper);
        if(null == sound){
            return null;
        }
        UserRecord userRecord = new UserRecord(null,user.getId().intValue(),sound.getId().intValue());
        userRecordMapper.insert(userRecord);

        Long userId = sound.getUserId();
        UserInfo userInfo = this.userInfoService.queryUserInfoById(userId);
        if(null == userInfo){
            return null;
        }

        SoundVo soundVo = new SoundVo();
        soundVo.setAge(userInfo.getAge());
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setGender(userInfo.getSex().equals("男") ? "man" : "woman");
        soundVo.setNickname(userInfo.getNickName());
        soundVo.setSoundUrl(sound.getSoundUrl());
        soundVo.setId(Integer.parseInt(userId.toString()));

        //第一次
        String soundKey = "SOUND_" + user.getId();
        if(!this.redisTemplate.hasKey(soundKey)){
            this.redisTemplate.opsForValue().set(soundKey,"1", Duration.ofDays(1));
        }else {
            String key = this.redisTemplate.opsForValue().get(soundKey);

            if(StringUtils.isNotBlank(key)){
                if(Integer.parseInt(key) >= 10){
                    soundVo.setRemainingTimes(0);
                }else {
                    soundVo.setRemainingTimes(10 - Integer.parseInt(key));
                    this.redisTemplate.opsForValue().increment(soundKey);
                }
            }
        }
        return soundVo;
    }
}
